package com.example.test.mutiple;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server2 {
    private ServerSocket serverSocket;
    public static void main(String[] args) {
        Server2 server = new Server2(321);
        server.start();
    }
    public Server2(int port) {
        try {
            this.serverSocket = new ServerSocket(port);
            System.out.println("MySocketServer服务端启动成功! 端口:" + port);
        } catch (IOException exception) {
            System.out.println("MySocketServer服务端启动失败!");
        }
    }
    private void start() {
        new Thread(() -> {
            while (true) {
                try {
                    Socket client = serverSocket.accept();
                    new MyClientHandler(client).start();
                } catch (IOException e) {
                    System.out.println("服务端异常!");
                }
            }
        }).start();
    }
}
class MyClientHandler {
    public static final int MAX_DATA_LEN = 1024;
    private final Socket socket;

    public MyClientHandler(Socket socket) {
        this.socket = socket;
    }
    public void start() {
        System.out.println("新客户端接入");
        new Thread(() -> doStart()).start();
    }
    private void doStart() {
        try {
            InputStream inputStream = socket.getInputStream();
            while (true) {
                byte[] data = new byte[MAX_DATA_LEN];
                int len;
                while ((len = inputStream.read(data)) != -1) {
                    String message = new String(data, 0, len);
                    System.out.println("从客户端 " + socket.getLocalPort()+" 接收数据: " + message);
                    socket.getOutputStream().write(data);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

